package fun.lifepoem.blog.controller;

import fun.lifepoem.blog.common.DateEnum;
import fun.lifepoem.blog.common.RedisKeys;
import fun.lifepoem.blog.common.RestResponse;
import fun.lifepoem.blog.common.annotation.ApiCtlLog;
import fun.lifepoem.blog.controller.base.BaseController;
import fun.lifepoem.blog.domain.dto.ArticleListConditionDTO;
import fun.lifepoem.blog.domain.vo.ArticleVO;
import fun.lifepoem.blog.service.ArticleService;
import fun.lifepoem.blog.service.RedisService;
import fun.lifepoem.blog.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author Yiwyn
 * @create 2022/9/25 0:08
 */
@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisService redisService;

    @ApiCtlLog
    @PostMapping("/list")
    public RestResponse<List<ArticleVO>> getArticleList(@RequestBody ArticleListConditionDTO conditionDTO) {
        conditionDTO.setSize(Optional.ofNullable(conditionDTO.getSize()).orElse(9999));
        conditionDTO.setStart(Optional.ofNullable(conditionDTO.getStart()).orElse(0) * conditionDTO.getSize());

        List<ArticleVO> articleList;
        //当查询所有tag下的文章的时候，进入缓存。
        if (!StringUtils.hasText(conditionDTO.getTagId())) {
            String date = DateUtils.getInstance().getDate(DateEnum.DATE_DAY);
            String key = RedisKeys.ALL_ARTICLE + date;
            articleList = (List<ArticleVO>) redisService.getKey(key);
            if (articleList != null) {
                return doSuccess(articleList);
            } else {
                articleList = articleService.getArticleList(conditionDTO);
                redisService.setKey(key, articleList, 24, TimeUnit.HOURS);
                return doSuccess(articleList);
            }
        }
        articleList = articleService.getArticleList(conditionDTO);
        return doSuccess(articleList);
    }


    @ApiCtlLog
    @GetMapping("/getArticle")
    public RestResponse<ArticleVO> getArticleById(String articleId) {
        ArticleVO article = articleService.getArticleById(articleId);
        if (ObjectUtils.isEmpty(article)) {
            return doError("没有获取到相关文章");
        }
        return doSuccess(article);
    }

    /**
     * 添加文章，支持用户自定义文章的添加
     *
     * @return
     */
    @ApiCtlLog
    @PostMapping("/add")
    public RestResponse<String> addArticle() {

        return null;
    }


}
